package com.example.anni.zhuzhoujia.tianya12345;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.example.anni.zhuzhoujia.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 杨胜文的同城
 */
public class CityFragment extends Fragment {
    public ListView list_item;
    public List<Map<String, Object>> list;
    public List<Map<String, Object>> list1;
    public JSONArray data;
    public JSONArray data1;
    public String title;
    public String startLine;
    public String endLine;
    public String address;
    public String nickName;
    public String user;
    public String avatar;
    public String gender;
    public String images;
    public int partIn;//当前参加人数
    public int peoples;//人数上限
    public String dateline;//发表时间
    public String id;
    public String[] imagesArray;
    public ImageView establish;
    public int index1;//滚动下标
    public int index2;
    PtrClassicFrameLayout ptrClassicFrameLayout;
    Handler handler = new Handler();
    int page;
    View root;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LinearLayout root = (LinearLayout) inflater.inflate(R.layout.city_list_view, null);
        //调用登录接口
        RequestParams params1 = new RequestParams("http://tr.zzapi.gson.cn/api/user/login");
        params1.addBodyParameter("userName", "测试");
        params1.addBodyParameter("password", "666666");
        x.http().post(params1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {

            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
        return root;
    }

    private void initData() {

    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ptrClassicFrameLayout = (PtrClassicFrameLayout) view.findViewById(R.id.test_list_view_frame);
        list_item = (ListView) view.findViewById(R.id.list_item);
        initData();
        listData();
        root = LayoutInflater.from(getActivity()).inflate(R.layout.city_header, null);
        list_item.addHeaderView(root, "18182082473", false);
        //获取创建活动图标的id
        establish = (ImageView) view.findViewById(R.id.establish);
        //创建活动图标的单击事件
        establish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CityEstablish.class);
                startActivity(intent);
            }
        });
    }

    public void listData() {
        page = 1;
        list = new ArrayList<>();
        x.view().inject(getActivity());
        RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/activity/list?page=" + page + "&rows=15");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                com.alibaba.fastjson.JSONObject json = JSON.parseObject(s);
                data = json.getJSONArray("data");
                //创建适配器
                class DiscloseAdapter extends BaseAdapter {
                    public DiscloseAdapter() {
                        for (int i = 0; i < data.size(); i++) {
                            JSONObject obj1 = data.getJSONObject(i);
                            title = obj1.getString("title");
                            startLine = obj1.getString("startLine");
                            endLine = obj1.getString("endLine");
                            address = obj1.getString("address");
                            user = obj1.getString("user");
                            images = obj1.getString("images");
                            partIn = obj1.getInteger("partIn");
                            peoples = obj1.getInteger("peoples");
                            id = obj1.getString("id");
                            dateline = obj1.getString("dateline");

                            JSONObject obj2 = JSON.parseObject(user);
                            nickName = obj2.getString("nickName");
                            avatar = obj2.getString("avatar");
                            gender = obj2.getString("gender");
                            Map<String, Object> map = new HashMap<>();
                            map.put("title", title);
                            map.put("startLine", startLine);
                            map.put("endLine", endLine);
                            map.put("address", address);
                            map.put("nickName", nickName);
                            map.put("id", id);
                            map.put("avatar", avatar);
                            map.put("gender", gender);
                            map.put("images", images);
                            map.put("partIn", partIn);
                            map.put("peoples", peoples);
                            map.put("dateline", dateline);
                            list.add(map);
                        }
                    }

                    public int getCount() {
                        return list.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return list.get(position);
                    }

                    @Override
                    public long getItemId(int position) {
                        return position;
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        final LayoutTextView5 layoutTextView5;
                        if (convertView == null) {
                            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.city_fragment, null);
                            layoutTextView5 = new LayoutTextView5();
                            layoutTextView5.tv_title = (TextView) convertView.findViewById(R.id.title);
                            layoutTextView5.tv_startLine = (TextView) convertView.findViewById(R.id.startLine);
                            layoutTextView5.tv_endLine = (TextView) convertView.findViewById(R.id.endLine);
                            layoutTextView5.tv_address = (TextView) convertView.findViewById(R.id.address);
                            layoutTextView5.tv_nickName = (TextView) convertView.findViewById(R.id.nickName);
                            layoutTextView5.tv_avatar = (ImageView) convertView.findViewById(R.id.avatar);
                            layoutTextView5.tv_gender = (ImageView) convertView.findViewById(R.id.gender);
                            layoutTextView5.tv_yes_no = (TextView) convertView.findViewById(R.id.yes_no);
                            layoutTextView5.tv_img = (ImageView) convertView.findViewById(R.id.img);
                            layoutTextView5.tv_dateline = (TextView) convertView.findViewById(R.id.dateline);
                            layoutTextView5.tv_partIn = (TextView) convertView.findViewById(R.id.partIn);
                            layoutTextView5.tv_peoples = (TextView) convertView.findViewById(R.id.peoples);
                            layoutTextView5.tv_pictureNumber = (TextView) convertView.findViewById(R.id.pictureNumber);
                            layoutTextView5.line_pictureNumber = (LinearLayout) convertView.findViewById(R.id.line_pictureNumber);
                            convertView.setTag(layoutTextView5);
                        } else {
                            layoutTextView5 = (LayoutTextView5) convertView.getTag();
                        }
                        //设置头像
                        ImageOptions options = new ImageOptions.Builder()
                                .setRadius(20)//圆角矩形的弧度
                                .setSquare(true)//设置圆角矩形
                                .setCircular(true)//设置圆形
                                .setLoadingDrawableId(R.mipmap.default_avatar)//加载过程中的等待图片
                                .setFailureDrawableId(R.mipmap.default_avatar)//加载出错显示的图片
                                .build();
                        //显示远程图片
                        x.image().bind(
                                layoutTextView5.tv_avatar,
                                "http://tr.zzapi.gson.cn/" + list.get(position).get("avatar"),
                                options
                        );
                        //设置性别图标
                        String gender = list.get(position).get("gender") + "";
                        if (gender.equals("BOY")) {
                            layoutTextView5.tv_gender.setImageResource(R.mipmap.boy);
                        } else {
                            layoutTextView5.tv_gender.setImageResource(R.mipmap.girl);
                        }
                        //提示是否可以参加此活动
                        int partIn1 = (int) list.get(position).get("partIn");
                        int peoples1 = (int) list.get(position).get("peoples");
                        layoutTextView5.tv_partIn.setText(partIn1 + "/");
                        layoutTextView5.tv_peoples.setText(peoples1 + "");
                        if (partIn1 < peoples1) {
                            layoutTextView5.tv_yes_no.setText("人员未满");
                            layoutTextView5.tv_yes_no.setTextColor(0xFF33CC99);
                        } else {
                            layoutTextView5.tv_yes_no.setText("人员已满");
                            layoutTextView5.tv_yes_no.setTextColor(0xFFCC3300);
                        }
                        //活动图片
                        //如果没有图片，则隐藏存放图片的LinearLayout
                        String img = list.get(position).get("images") + "";
                        if (img == null || img.length() == 0) {
                            layoutTextView5.tv_img.setVisibility(View.GONE);
                            layoutTextView5.line_pictureNumber.setVisibility(View.GONE);
                        } else {
                            layoutTextView5.tv_img.setVisibility(View.VISIBLE);
                            layoutTextView5.line_pictureNumber.setVisibility(View.VISIBLE);
                        }
                        imagesArray = img.split(",");
                        //设置图片
                        ImageOptions options1 = new ImageOptions.Builder()
                                .build();
                        //显示远程图片
                        x.image().bind(
                                layoutTextView5.tv_img,
                                "http://tr.zzapi.gson.cn/" + imagesArray[0],
                                options1
                        );

                        String startLine = list.get(position).get("startLine") + "";//开始时间
                        String endLine = list.get(position).get("endLine") + "";//结束时间
                        layoutTextView5.tv_title.setText((String) list.get(position).get("title"));
                        layoutTextView5.tv_startLine.setText(startLine.substring(0, 10));
                        layoutTextView5.tv_endLine.setText(endLine.substring(0, 10));
                        layoutTextView5.tv_address.setText("" + list.get(position).get("address"));
                        layoutTextView5.tv_nickName.setText("" + list.get(position).get("nickName"));
                        layoutTextView5.tv_pictureNumber.setText(imagesArray.length + "");//图片数量
                        //获得系统时间
                        Calendar c = Calendar.getInstance();
                        int year = c.get(Calendar.YEAR);//年
                        int month = c.get(Calendar.MONTH) + 1;//月
                        int day = c.get(Calendar.DAY_OF_MONTH);//日
                        int hour = c.get(Calendar.HOUR_OF_DAY);//时
                        int minute = c.get(Calendar.MINUTE);//分
                        String months = month + "";
                        String days = day + "";
                        if (months.length() == 1) {
                            months = "0" + month;
                        }
                        if (days.length() == 1) {
                            days = "0" + day;
                        }
                        String time = year + "-" + months + "-" + days;
                        String date = "" + list.get(position).get("dateline");//服务器上的日期
                        //如果获得的日期与系统相等则显示今天
                        if (time.equals(date.substring(0, 10))) {
                            layoutTextView5.tv_dateline.setText("今天" + date.substring(10));
                        } else {
                            layoutTextView5.tv_dateline.setText("" + list.get(position).get("dateline"));
                        }
                        return convertView;
                    }
                }
                //添加Header 必须要放在BaseAdapter的前面
                LinearLayout notStart = (LinearLayout) root.findViewById(R.id.notStart);
                LinearLayout alreadyStarted = (LinearLayout) root.findViewById(R.id.alreadyStarted);
                LinearLayout hasEnded = (LinearLayout) root.findViewById(R.id.hasEnded);
                LinearLayout myActivities = (LinearLayout) root.findViewById(R.id.myActivities);
                //未开始活动监听器
                notStart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), CityActivity.class);
                        intent.putExtra("Interface", "api/activity/list/unBegin");//把接口传过去
                        intent.putExtra("title", "未开始活动");//把标题传过去
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.ysw_a_in, R.anim.ysw_out);
                    }
                });
                //已开始活动监听器
                alreadyStarted.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), CityActivity.class);
                        intent.putExtra("Interface", "api/activity/list/begin");//把接口传过去
                        intent.putExtra("title", "已开始活动");//把标题传过去
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.ysw_a_in, R.anim.ysw_out);
                    }
                });
                //已结束活动监听器
                hasEnded.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), CityActivity.class);
                        intent.putExtra("Interface", "api/activity/list/endBegin");//把接口传过去
                        intent.putExtra("title", "已结束活动");//把标题传过去
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.ysw_a_in, R.anim.ysw_out);
                    }
                });
                //我的活动监听器
                myActivities.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), CityMyActivity.class);
                        intent.putExtra("Interface", "api/activity/list/endBegin");//把接口传过去
                        intent.putExtra("title", "我的活动");//把标题传过去
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.ysw_b_in, R.anim.ysw_out);
                    }
                });
                /*//添加适配器
                BaseAdapter a = new DiscloseAdapter();
                a.notifyDataSetChanged();
                list_item.setAdapter(a);
                //查看活动详情
                list_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //从适配器获取数据,添加了表头之后必须把BaseAdapter改成HeaderViewListAdapter，不然列表项的内容与获取的内容不一样
                        HeaderViewListAdapter hvla = (HeaderViewListAdapter) parent.getAdapter();
                        //从列表项获取数据
                        Map<String, String> m = (Map<String, String>) hvla.getItem(position);
                        Intent intent = new Intent(getActivity(), CityDetails.class);
                        intent.putExtra("id", m.get("id"));//把id变成字符串
                        startActivity(intent);
                    }
                });*/
                //添加适配器
                final BaseAdapter a = new DiscloseAdapter();
                a.notifyDataSetChanged();
                list_item.setAdapter(a);
                //查看活动详情
                list_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //从适配器获取数据,添加了表头之后必须把BaseAdapter改成HeaderViewListAdapter，不然列表项的内容与获取的内容不一样
                        HeaderViewListAdapter hvla = (HeaderViewListAdapter) parent.getAdapter();
                        //从列表项获取数据
                        Map<String, String> m = (Map<String, String>) hvla.getItem(position);
                        Intent intent = new Intent(getActivity(), CityDetails.class);
                        intent.putExtra("id", m.get("id"));//把id变成字符串
                        startActivity(intent);
                    }
                });
                ptrClassicFrameLayout.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        ptrClassicFrameLayout.autoRefresh(true);
                    }
                }, 150);

                ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {

                    @Override
                    public void onRefreshBegin(PtrFrameLayout frame) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
//                                page ++;
                                listData();
//                                Toast.makeText(getActivity(),"刷新成功",Toast.LENGTH_LONG).show();
                                a.notifyDataSetChanged();
                                ptrClassicFrameLayout.refreshComplete();
                                ptrClassicFrameLayout.setLoadMoreEnable(true);
                            }
                        }, 1000);
                    }
                });
                RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/activity/list?page=" + 2 + "&rows=15");
                x.http().get(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String s) {
                        com.alibaba.fastjson.JSONObject json = JSON.parseObject(s);
                        data1 = json.getJSONArray("data");
                        list1 = new ArrayList<>();
                        for (int i = 0; i < data1.size(); i++) {
                            JSONObject obj1 = data1.getJSONObject(i);
                            String title = obj1.getString("title");
                            String startLine = obj1.getString("startLine");
                            String endLine = obj1.getString("endLine");
                            String address = obj1.getString("address");
                            String user = obj1.getString("user");
                            String images = obj1.getString("images");
                            int partIn = obj1.getInteger("partIn");
                            int peoples = obj1.getInteger("peoples");
                            String id = obj1.getString("id");
                            String dateline = obj1.getString("dateline");
                            JSONObject obj2 = JSON.parseObject(user);
                            String nickName = obj2.getString("nickName");
                            String avatar = obj2.getString("avatar");
                            String gender = obj2.getString("gender");
                            Map<String, Object> map = new HashMap<>();
                            map.put("title", title);
                            map.put("startLine", startLine);
                            map.put("endLine", endLine);
                            map.put("address", address);
                            map.put("nickName", nickName);
                            map.put("id", id);
                            map.put("avatar", avatar);
                            map.put("gender", gender);
                            map.put("images", images);
                            map.put("partIn", partIn);
                            map.put("peoples", peoples);
                            map.put("dateline", dateline);
                            list1.add(map);
                        }
                        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                            @Override
                            public void loadMore() {
                                handler.postDelayed(new Runnable() {

                                    @Override
                                    public void run() {
                                        for (int i = 0; i < data1.size(); i++) {
                                            JSONObject obj1 = data1.getJSONObject(i);
                                            String title = obj1.getString("title");
                                            String startLine = obj1.getString("startLine");
                                            String endLine = obj1.getString("endLine");
                                            String address = obj1.getString("address");
                                            String user = obj1.getString("user");
                                            String images = obj1.getString("images");
                                            int partIn = obj1.getInteger("partIn");
                                            int peoples = obj1.getInteger("peoples");
                                            String id = obj1.getString("id");
                                            String dateline = obj1.getString("dateline");

                                            JSONObject obj2 = JSON.parseObject(user);
                                            nickName = obj2.getString("nickName");
                                            avatar = obj2.getString("avatar");
                                            gender = obj2.getString("gender");
                                            Map<String, Object> map = new HashMap<>();
                                            map.put("title", title);
                                            map.put("startLine", startLine);
                                            map.put("endLine", endLine);
                                            map.put("address", address);
                                            map.put("nickName", nickName);
                                            map.put("id", id);
                                            map.put("avatar", avatar);
                                            map.put("gender", gender);
                                            map.put("images", images);
                                            map.put("partIn", partIn);
                                            map.put("peoples", peoples);
                                            map.put("dateline", dateline);
                                            list.add(map);
                                        }
                                        list_item.setSelection(list_item.getAdapter().getCount() - 1);//自动滚动到最底部
                                        a.notifyDataSetChanged();
                                        ptrClassicFrameLayout.loadMoreComplete(true);
                                        page++;

                                    }
                                }, 2000);
                            }
                        });
                        page++;
                    }

                    @Override
                    public void onError(Throwable throwable, boolean b) {

                    }

                    @Override
                    public void onCancelled(CancelledException e) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });

            }

            class LayoutTextView5 {
                public TextView tv_title;
                public TextView tv_startLine;
                public TextView tv_endLine;
                public TextView tv_address;
                public TextView tv_nickName;
                public ImageView tv_avatar;
                public ImageView tv_gender;
                public TextView tv_yes_no;
                public ImageView tv_img;
                public TextView tv_dateline;
                public TextView tv_partIn;
                public TextView tv_peoples;
                public TextView tv_pictureNumber;
                public LinearLayout line_pictureNumber;
            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
